<?php

class ImageUploader{

	private $posted_image;
	private $extension;

	function __construct($posted_image){
		if($posted_image["error"] == 0){
			$name_parts = explode(".", $posted_image["name"]);
        	$extension = $name_parts[sizeof($name_parts) - 1];
			
			if($this->validExtension($extension)){
				$this->extension = strtolower($extension);
				$this->posted_image = $posted_image;
			
			} else {
				throw new Exception("not a valid image (png, gif, bmp, jpg, jpeg)");
			}
		
		} else {
			throw new Exception("fail to upload " . $posted_image["error"]);
		}
	}

	private function validExtension($extension){
		$extensions = array("bmp", "png", "gif", "jpg", "jpeg");
		return in_array(strtolower($extension), $extensions);
	}

	public function getExtension(){
		return $this->extension;
	}

	public function store(){
		list($msec, $sec) = explode(" ", microtime());
		$name = sha1($msec.$sec) . "." .$this->getExtension();
		$path = "images/products/".$name;
		move_uploaded_file($this->posted_image["tmp_name"], $path);
		
		return $path;
	}

}
?>
